package mspbots.data.tl.prod.autotask.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.entity.ResultEntity;
import mspbots.data.tl.prod.autotask.mapper.TaskAutoDepartmentMapper;
import mspbots.data.tl.prod.autotask.model.TaskAutotaskDepartment;
import mspbots.data.tl.prod.autotask.model.TaskAutotaskProject;
import mspbots.data.tl.prod.autotask.service.TaskAutotaskDepartmentService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


/**
 * @author aff
 */
@Service
@Log4j2
@RequiredArgsConstructor
@DS("master")
public class TaskAutotaskDepartmentServiceImpl extends AbstractBaseServiceImpl<TaskAutoDepartmentMapper, TaskAutotaskDepartment>
        implements TaskAutotaskDepartmentService {


    @Override
    public void sync(ResultEntity content) {


        log.debug("Autotask department receiver content {}", content);
        JsonNode entity = content.getEntity();
        TaskAutotaskDepartment data = TaskAutotaskDepartment.builder()
                .departmentId(super.getLongValue(entity.get("id")))
                .name(ObjectUtils.isEmpty(entity.get("name")) ? null : entity.get("name").asText())
                .number(ObjectUtils.isEmpty(entity.get("number")) ? null : entity.get("number").asText())
                .description(ObjectUtils.isEmpty(entity.get("description")) ? null : entity.get("description").asText())
                .primaryLocationId(ObjectUtils.isEmpty(entity.get("primaryLocationID")) ? null : entity.get("primaryLocationID").asLong())
                .syncTime(LocalDateTime.now())
                .build();

        data.setTenantCode(content.getTenantId());


        TaskAutotaskDepartment dbData = super.baseMapper.selectOne(Wrappers.<TaskAutotaskDepartment>lambdaQuery()
                .eq(TaskAutotaskDepartment::getTenantCode, data.getTenantCode())
                .eq(TaskAutotaskDepartment::getDepartmentId, data.getDepartmentId())
                .last("limit 1"));
        if (ObjectUtils.isEmpty(dbData)) {
            super.baseMapper.insert(data);
        } else {
            data.setId(dbData.getId());
            super.baseMapper.updateById(data);
        }


    }
}
